import { login, sysProfile, sysUser } from '@/api/user'
import { getToken, setToken } from '@/utils/auth'
import asyncRouters from '@/router/modules/index.js'
import router from '@/router'
import { constantRoutes,resetRouter } from '@/router'

const state = {
  token: getToken() || '',
  userInfo: ''
}
const mutations = {
  setToken(state, value) {
    state.token = value
    setToken(value)
  },
  setUserInfo(state, value) {
    state.userInfo = value
  },
  logout(state) {
    state.token = ''
    setToken('')
    state.userInfo = ''
    // 调用重置路由方法重置路由  假如不用,在不刷新情况下,退出了账号,登录新账号,路由信息还是原账号的
    resetRouter()
  }
}
const actions = {
  // 登录
  async isLogin({ commit }, value) {
    const res = await login(value)
    // console.log(res)
    commit('setToken', res.data)
  },
  // 获取用户全部信息并存储
  async getUserInfo({ commit, state }) {
    // 获取用户个人信息
    const res = await sysProfile()
    // 获取员工基本信息
    const res2 = await sysUser(res.data.userId)
    // 保存用户信息  2个对象合并
    commit('setUserInfo', { ...res.data, ...res2.data })
    // console.log('state', state.userInfo)
    // console.log('个人用户信息', res)
    // console.log('员工个人信息', res2)

    const newRouters = asyncRouters.filter((item) => {
      return state.userInfo.roles.menus.includes(item.meta.name)
    })
    // 404报错添加到动态匹配路由中
    newRouters.push({ path: '*', redirect: '/404', hidden: true })
    // 把筛选出来的(动态匹配)路由添加到路由中
    router.addRoutes(newRouters)
    // 调用routes  拼接路由
    commit('routes/setRouteList', [...constantRoutes,...newRouters], { root: true })
    // addRoutes 的缺陷,需要再经历一次导航守卫才能正常访问,需要把404报错放到动态匹配路由中

    console.log(newRouters)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
